import api from "../../utils/api";
import Utils from "../../utils/utils";

// pages/orderinfo/orderinfo.ts
Page({

  /**
   * 页面的初始数据
   */
  data: {
    height: 0 as number,
    activeIndex: -1 as number,
    order: [
      {
        title: "全部",
        list: [],
        type: 0,
        value: "",
        page: 1,
        totalCount: 0,
      },
      {
        title: "待付款",
        list: [],
        type: 1,
        value: "PAYING",
        page: 1,
        totalCount: 0
      },
      {
        title: "处理中", list: [], type: 2, value: 'PROCESSING', page: 1,
        totalCount: 0
      },
      {
        title: "已完成", list: [], type: 3, value: 'FINISHED', page: 1,
        totalCount: 0
      },
      {
        title: "售后", list: [], type: 4, value: "POST_SALE", page: 1,
        totalCount: 0
      },
    ] as Status[],
    pageSize: 10 as number,
    isLoading: false as boolean,//是否正在加载
    orderStatusMap: {
      WAITING_SEND: '待发货',
      DELIVERY_LOCKED: '待发货',
      REFUND_REJECTED: '待发货',
      REDELIVERY_LOCKED: '待发货',
      DELIVERING: '商品已发出',
      DELIVERING_NO_RETURN: '商品已发出',
      REDELIVERING: '商品已发出',
      FINISHED: '已完成',
      CANCELED: '已取消',
      CANCELED_REFUND: '已取消',
      RETURN_APPLIED: '售后处理中',
      REFUND_FINISHED: '已退款',
      RETURN_AGREED: "已同意退货",
      RETURN_SENT: '售后处理中',
      PAYING:'待支付'
    },
  },

  /**
   * 生命周期函数--监听页面加载 
   */
  onLoad(options: any) {
    const status = options.status
    const activeIndex = this.data.order.findIndex(item => {
      return item.value === status
    })
    this.setData({
      activeIndex
    })

  },

  // 计算高度
  calcHeight(): void {
    let className;
    if (this.data.order[this.data.activeIndex].list.length !== 0) {
      className = "order_" + this.data.activeIndex
    } else {
      className = "empty"
    }
    const that = this;
    const systemInfo = wx.getSystemInfoSync();
    const scale = 750 / systemInfo.windowWidth;
    wx.createSelectorQuery().select(`.${className}`).boundingClientRect(function (rect) {
      that.setData({
        height: rect.height * scale
      })
    }).exec();
  },
  // 切换
  slideOn(e: any): void {
    const status = this.data.order[e.detail.current].value
    this.setData({
      activeIndex: e.detail.current,
    })
    this.getOrderList(status).then(() => {
      this.calcHeight();
    })
  },
  changeItem(e: any): void {
    this.setData({
      activeIndex: e.currentTarget.dataset.index,
    });
  },
  // 获取订单列表
  async getOrderList(status: string): Promise<void> {
    if (this.data.isLoading) {
      return
    }
    const { pageSize, order, activeIndex } = this.data
    const page = order[activeIndex].page
    const params = {
      status,
      page,
      pageSize
    }
    // 如果之前加载过数据，判断是否已经加载完毕
    if (order[activeIndex].totalCount == order[activeIndex].list.length && order[activeIndex].totalCount != 0) {
      return
    }
    this.setData({
      isLoading: true
    })
    const res = await api.order.getOrderList(params)
    if (res.data.code == "000") {
      const data = res.data.data
      if (data && data.list) {
        data.list.forEach(item => {
          item.totalAmount = Utils.priceToYuan(item.totalAmount as number)
          item.orderTime = Utils.timestampToDateTime(item.orderTime as number)
          if (item.orderContents) {
            item.orderContents.forEach(order => {
              order.price = Utils.priceToYuan(order.price as number)
            })
          }
        })
        order[activeIndex].list = [...order[activeIndex].list, ...data.list]
        order[activeIndex].page += 1
        order[activeIndex].totalCount = data.totalCount as number
        this.setData({
          order,
        })
      }
      this.setData({
        isLoading: false
      })
    } else {
      this.setData({
        isLoading: false
      })
      wx.showToast({
        title: res.data.message as string,
        icon: "error"
      })
    }
  },
  // 查看物流
  toLogistics(e: any): void {
    const id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: "/pages/logisticsdetail/logisticsdetail?type=order&id=" + id
    })
  },
  // 去详情
  toOrderDetail(e: any): void {
    const id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: "/pages/orderdetail/orderdetail?id=" + id
    })
  },
  // 去详情支付
  toPay(e: any): void {
    const id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: "/pages/orderdetail/orderdetail?id=" + id + "&pay=1"
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    const { order, activeIndex } = this.data
    const status = order[activeIndex].value
    order[activeIndex].page = 1
    order[activeIndex].totalCount = 0
    order[activeIndex].list = []
    this.setData({
      order
    })
    this.getOrderList(status).then(() => {
      this.calcHeight();
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    const { order, activeIndex } = this.data
    if (order[activeIndex].list.length == order[activeIndex].totalCount) {
      return
    }
    const status = order[activeIndex].value
    this.getOrderList(status).then(() => {
      this.calcHeight();
    })
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})